
#include "syscall.h"

int main(int argc, char** argv)
{
   int ret = 0;
   char* filename = "hello.txt";
   char* toWrite = "hello world";

   //creat
   int fd = 0;
   if( ret == 0 ) {
      fd = creat( filename );
      if( fd != -1 ) {
         printf( "FileDescriptor for %s is %d\n", filename, fd );
      } else {
         printf( "error: could not create file: %s\n", filename );
         ret = -1;
      }
   }

   //close fd for creat 
   //       after creat, we don't need FileDescriptor fd, so close it and
   //       if it's number gets reused, we know close() worked.
   int closeRetVal = 0;
   if( ret == 0 ) {
      closeRetVal = close( fd );
      if( closeRetVal == 0 ) {
         printf( "FileDescriptor %d closed successfully\n", fd );
      } else {
         printf( "error: could not close file: %s with fd: %d\n", 
                 filename, fd );
         ret = -5;
      }
   }

   //open
   int fd2 = 0;
   if( ret == 0 ) {
      fd2 = open( filename );
      if( fd2 != -1 ) {
         printf( "FileDescriptor for %s is %d\n", filename, fd2 );
      } else {
         printf( "error: could not open file: %s\n", filename );
         ret = -2;
      }
   }

   //test-close()  --  assume no other processes got fd
   if( fd == fd2 ) {
      printf( "Close Succeeded\n" );
   } else {
      printf( "error: close failed: fd=%d and fd2=%d\n", fd, fd2 );
      ret = -6;
   }

   //write
   int bytesWritten = 0;
   if( ret == 0 ) {
      bytesWritten = write( fd2, toWrite, strlen(toWrite));
      if( bytesWritten > 0 ) {
         printf( "Wrote %d bytes of \"%s\" to %s\n", 
                 bytesWritten, toWrite, filename );
      } else {
         printf( "error: could not write %s to file: %s\n", 
                 toWrite, filename );
         ret = -3;
      }
   }

   //read
   int bytesRead = 0;
   char dataRead[256];
   if( ret == 0 ) {
      bytesRead = read( fd2, dataRead, bytesWritten );
      if( bytesWritten > 0 ) {
         printf( "Read %d bytes of \"%s\" from %s\n", 
                 bytesRead, dataRead, filename );
      } else {
         printf( "error: could not read %d bytes from file: %s\n", 
                 bytesWritten, filename );
         ret = -4;
      }
   }

   //close fd for write/read
   if( ret == 0 ) {
      closeRetVal = close( fd2 );
      if( closeRetVal == 0 ) {
         printf( "FileDescriptor %d closed successfully\n", fd2 );
      } else {
         printf( "error: could not close file: %s with fd: %d\n", 
                 filename, fd2 );
         ret = -7;
      }
   }

   //unlink
   int unlinkRetVal = 0;
   if( ret == 0 ) {
      unlinkRetVal = unlink( filename );
      if( unlinkRetVal == 0 ) {
         printf( "File %s unlinked successfully\n", filename );
      } else {
         printf( "error: could not unlink file: %s\n", filename );
         ret = -8;
      }
   }

   return ret;
}
